import { ref, watch, onMounted } from 'vue'

// 主题类型
export type Theme = 'light' | 'dark'

// 主题状态
const currentTheme = ref<Theme>('light')
const isDark = ref(false)

// 应用主题到 DOM
const applyTheme = (theme: 'light' | 'dark') => {
  if (typeof document === 'undefined') return
  
  const root = document.documentElement
  
  if (theme === 'dark') {
    root.setAttribute('data-theme', 'dark')
    isDark.value = true
  } else {
    root.removeAttribute('data-theme')
    isDark.value = false
  }
}

// 更新主题
const updateTheme = () => {
  applyTheme(currentTheme.value)
}

// 主题切换 Hook
export const useTheme = () => {
  // 设置主题
  const setTheme = (theme: Theme) => {
    currentTheme.value = theme
    localStorage.setItem('blog-theme', theme)
    updateTheme()
  }
  
  // 切换到下一个主题
  const toggleTheme = () => {
    const themes: Theme[] = ['light', 'dark']
    const currentIndex = themes.indexOf(currentTheme.value)
    const nextIndex = (currentIndex + 1) % themes.length
    setTheme(themes[nextIndex])
  }
  
  // 获取主题图标
  const getThemeIcon = () => {
    switch (currentTheme.value) {
      case 'light':
        return 'Sunny'
      case 'dark':
        return 'Moon'
      default:
        return 'Sunny'
    }
  }
  
  // 获取主题文本
  const getThemeText = () => {
    switch (currentTheme.value) {
      case 'light':
        return '浅色模式'
      case 'dark':
        return '深色模式'
      default:
        return '浅色模式'
    }
  }
  
  // 初始化主题
  const initTheme = () => {
    // 从本地存储读取主题设置
    const savedTheme = localStorage.getItem('blog-theme') as Theme
    if (savedTheme && ['light', 'dark'].includes(savedTheme)) {
      currentTheme.value = savedTheme
    } else {
      // 默认浅色模式
      currentTheme.value = 'light'
    }
    
    updateTheme()
  }
  
  
  // 监听主题变化
  watch(currentTheme, updateTheme, { immediate: true })
  
  return {
    currentTheme: readonly(currentTheme),
    isDark: readonly(isDark),
    setTheme,
    toggleTheme,
    getThemeIcon,
    getThemeText,
    initTheme
  }
}

// 初始化全局主题
export const initGlobalTheme = () => {
  const { initTheme } = useTheme()
  initTheme()
}

// 只读引用，防止外部直接修改
const readonly = <T>(ref: any): Readonly<T> => ref